<?php
error_reporting(E_ALL ^ E_NOTICE);
$_K = array();
define('IN_KKFRAME', true);
define('ROOT', dirname(dirname(__FILE__)).'/');
define('SYSTEM_ROOT', ROOT.'/system/');
define('TIMESTAMP', $_K['timestamp'] = time());
header("Content-type: text/html; charset=utf-8");
@date_default_timezone_set('Asia/Shanghai');
ob_start();
include SYSTEM_ROOT.'function/core.php';
@include ROOT.'/data/config.php';
$step = $_GET['step'];
if($step && file_exists(ROOT.'data/install.lock')) $step = 'welcome';
switch($step){
	case '':
		_index();
		exit();
	case 'welcome':
		if(file_exists(ROOT.'data/install.lock')) _installed();
		@touch(ROOT.'/data/config.php');
		@touch(ROOT.'/data/avatar/index.html');
		if(!is_writable(ROOT.'/data/config.php')) _permission();
		if(!is_writable(ROOT.'/data/avatar/index.html')) _permission();
		@unlink(ROOT.'/data/config.php');
		@unlink(ROOT.'/data/avatar/index.html');
		_welcome();
		break;
	case 'mysql_setup':
		_output('<form method="post" action="?step=install" id="db_config" target="loader"><table class="config-table"><tr><td class="t">数据库服务器：</td><td><input type="text" name="db_server" value="localhost" /></td></tr><tr><td class="t">数据库用户名：</td><td><input type="text" name="db_username" /></td></tr><tr><td class="t">数据库密码：</td><td><input type="password" name="db_password" /></td></tr><tr><td class="t">数据库名：</td><td><input type="text" name="db_name" /></td></tr></table></form><p>注：如果输入的数据库中已有数据，安装 KKBBS 后原有数据将会被清除。建议选择新的数据库安装。</p>', '<a class="btn default" href="javascript:;" onclick="submit_form(\'db_config\');">开始安装</a>', '配置 MySQL 参数');
		break;
	case 'install':
		$_K['config']['security']['key'] = random(32);
		$_K['config']['forums']['0'] = '未分类';
		$_K['config']['style']['style_dir'] = 'default';
		$_K['config']['main']['sitename'] = 'KKBBS';
		$_K['config']['db']['server'] = $_POST['db_server'];
		$_K['config']['db']['username'] = $_POST['db_username'];
		$_K['config']['db']['password'] = $_POST['db_password'];
		$_K['config']['db']['charset'] = 'utf8';
		$_K['config']['db']['database'] = $_POST['db_name'];
		$_K['config']['db']['pconnect'] = 1;
		$db_link = mysql_connect($_K['config']['db']['server'], $_K['config']['db']['username'], $_K['config']['db']['password']);
		if(!$db_link) _output('<p>无法使用您提供的用户名 / 密码连接数据库服务器。</p>', '<a class="btn default" href="javascript:;" onclick="load_page(\'?step=mysql_setup\');">返回修改</a>', '系统错误');
		if(!mysql_select_db($_K['config']['db']['database'], $db_link)){
			if(!mysql_query('CREATE DATABASE '.daddslashes($_K['config']['db']['database']), $db_link)){
				_output('<p>抱歉，您指定的数据库不存在。</p><p>自动创建数据库失败。（没有新建数据库的权限）</p>', '<a class="btn default" href="javascript:;" onclick="load_page(\'?step=mysql_setup\');">返回修改</a>', '系统错误');
			}else{
				mysql_select_db($_K['config']['db']['database'], $db_link);
			}
		}
		$query = mysql_query('SHOW TABLES', $db_link);	// Clean database
		while ($currow = mysql_fetch_array($query)) {
			mysql_query("DROP TABLE IF EXISTS {$currow[0]}");
		}
		$sql = <<<EOF
CREATE TABLE `notice` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(11) unsigned NOT NULL,
  `time` int(10) unsigned NOT NULL,
  `content` text NOT NULL,
  `new` tinyint(1) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `uid` (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `post` (
  `pid` int(11) NOT NULL AUTO_INCREMENT,
  `tid` int(11) NOT NULL,
  `content` text COLLATE utf8_bin NOT NULL,
  `author` int(11) NOT NULL,
  `author_name` char(18) COLLATE utf8_bin NOT NULL,
  `time` int(10) unsigned NOT NULL,
  `deleted` tinyint(1) NOT NULL,
  PRIMARY KEY (`pid`),
  KEY `tid` (`tid`),
  KEY `author` (`author`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `thread` (
  `tid` int(11) NOT NULL AUTO_INCREMENT,
  `fid` int(11) NOT NULL,
  `author` int(11) NOT NULL,
  `author_name` char(18) COLLATE utf8_bin NOT NULL,
  `subject` char(128) CHARACTER SET utf8 NOT NULL,
  `desc` text COLLATE utf8_bin NOT NULL,
  `time` int(11) unsigned NOT NULL,
  `lastpost` int(11) unsigned NOT NULL,
  PRIMARY KEY (`tid`),
  KEY `author` (`author`),
  KEY `fid` (`fid`,`lastpost`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `user` (
  `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` char(18) COLLATE utf8_bin NOT NULL,
  `password` char(32) COLLATE utf8_bin NOT NULL,
  `email` char(64) COLLATE utf8_bin NOT NULL,
  `adminid` tinyint(4) NOT NULL,
  `ban` tinyint(1) NOT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
EOF;
		$errno = 0;
		foreach(explode(';', trim($sql)) as $query) {
			if(!$query) continue;
			mysql_query($query);
			if(mysql_errno()) _output('<p>安装过程中发生未知错误</p><p>错误消息：'.mysql_error().'</p>', '<a class="btn default" href="javascript:;" onclick="$(\'loader\').contentWindow.history.back();">返回</a>', '系统错误');
		}
		$config_data = '<?php if(defined(\'IN_KKFRAME\')) $_K[\'config\'] = '.var_export($_K['config'], true).'; ?>';
		file_put_contents(ROOT.'/data/config.php', $config_data);
		_output('<p>恭喜您，数据库配置成功！</p><br><p>不过，您还需要创建一个管理员账号，KKBBS 才能够正常运行。</p><form method="post" action="?step=admin_config" id="admin_config" target="loader"><table class="config-table"><tr><td class="t">用户名：</td><td><input type="text" name="username" /></td></tr><tr><td class="t">密码：</td><td><input type="password" name="password" /></td></tr><tr><td class="t">E-Mail：</td><td><input type="email" name="email" /></td></tr></table><input type="hidden" name="hash" value="'.md5($_K['config']['security']['key']).'" /></form>', '<a class="btn default" href="javascript:;" onclick="submit_form(\'admin_config\');">完成安装</a>', '管理员账号设置');
	case 'admin_config':
		if($_POST['hash'] != md5($_K['config']['security']['key']) || !$_K['config']['db']) _output('<p>KKBBS 来源错误，禁止访问此页面！</p><p>如果您在安装过程中遇到此问题，请重新运行安装程序。</p>', '<a class="btn default" href="javascript:;" onclick="load_page(\'?step=welcome\');">重新安装</a>', '系统错误');
		$db_link = mysql_connect($_K['config']['db']['server'], $_K['config']['db']['username'], $_K['config']['db']['password']);
		if(!$db_link) _output('<p>无法连接到数据库服务器。</p>', '', '系统错误');
		if(!mysql_select_db($_K['config']['db']['database'], $db_link)) _output('<p>抱歉，指定的数据库不存在。</p>', '', '系统错误');
		$username = daddslashes($_POST['username']);
		$password = md5($_POST['password']);
		$email = daddslashes($_POST['email']);
		$query = "INSERT INTO user SET username='{$username}', password='{$password}', email='{$email}', adminid='1', ban='0'";
		mysql_query($query);
		if(mysql_errno()) _output('<p>运行过程中发生未知错误</p><p>错误消息：'.mysql_error().'</p>', '<a class="btn default" href="javascript:;" onclick="$(\'loader\').contentWindow.history.back();">返回</a>', '系统错误');
		@touch(ROOT.'data/install.lock');
		dsetcookie('auth', authcode("1\t{$username}\t1", 'ENCODE'));
		_output('<p>恭喜您，KKBBS 已经可以正常运行了！</p><p>接下来，您可以进入后台设置进一步微调设置，或是回到首页享受 KKBBS 流畅的体验。</p><br><p>为保证安全，请及时删除本安装程序。</p>', '<a class="btn default" href="../" target="_blank">返回首页</a><a class="btn" href="../admin.php" target="_blank">系统设置</a>', '安装成功');
	default:
		_output('<p>KKBBS 安装程序遇到了一点小问题，暂时无法继续。</p>', '<a class="btn default" href="javascript:;" onclick="$(\'loader\').contentWindow.history.back();">返回</a>', '系统错误');
}

// Templates
function _output($contents, $btns = '', $title = 'KKBBS 安装程序'){
	echo <<<EOF
<div id="content">
<div class="title-bar with-btn">
<a href="javascript:;" class="btn-back" onclick="window.history.back();">Back</a>
<h1>{$title}</h1>
</div>
<div id="main">{$contents}</div>
<div id="btn-bar">{$btns}</div>
</div>
<script>window.parent.callback();</script>
EOF;
	exit();
}
function _welcome(){
	echo <<<EOF
<div id="content">
<div class="title-bar">
<h1>KKBBS 安装程序</h1>
</div>
<div id="main">
<p>欢迎使用 KKBBS 1.0！</p>
<p>当您看到此界面时，亦表示了 KKBBS 能运行于您当前的服务器环境上。</p>
<p>KKBBS 是全新一代的论坛系统，它创新性地采用了基于 PHP 构建的高效 KK Frame 框架，并融合了清新的用户界面（User Interface）。多亏了高效的 KK Frame 框架，KKBBS 在它极速运行的同时保障了界面的美观。根据实际测试，高效的 KKBBS 运行速度是同类产品 100 ~ 1000 倍！毫秒级的运算给您带来酣畅淋漓的使用体验。相信在使用的过程中，你一定会爱上 KKBBS。</p><br>
<p>好了，准备好你的 MySQL 账号信息，轻击下方按钮继续吧！</p>
</div>
<div id="btn-bar"><a class="btn default" href="javascript:;" onclick="load_page('?step=mysql_setup');">开始安装</a></div>
</div>
<script>window.parent.callback();</script>
EOF;
}
function _installed(){
	echo <<<EOF
<div id="content">
<div class="title-bar">
<h1>系统错误</h1>
</div>
<div id="main">
<p>您已经安装过了 KKBBS，安装程序无法继续。</p>
<p>要想重新安装 KKBBS，请手动删除 data/install.lock 文件。</p>
</div>
<div id="btn-bar"><a class="btn default" href="javascript:;" onclick="load_page('?step=welcome');">重试</a></div>
</div>
<script>window.parent.callback();</script>
EOF;
	exit();
}
function _permission(){
	echo <<<EOF
<div id="content">
<div class="title-bar">
<h1>权限错误</h1>
</div>
<div id="main">
<p>以下文件不可写入，请您修改权限：</p>
<p>/data/config.php</p>
<p>/data/avatar/</p>
</div>
<div id="btn-bar"><a class="btn default" href="javascript:;" onclick="load_page('?step=welcome');">重试</a></div>
</div>
<script>window.parent.callback();</script>
EOF;
	exit();
}
function _index(){
	echo <<<EOF
<!DOCTYPE html>
<html>
<head>
<title>KKBBS 安装程序</title>
<meta http-equiv="Content-Type" content="text/HTML; charset=utf-8">
<meta name="author" content="kookxiang" />
<meta name="copyright" content="KK's Laboratory" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<link rel="stylesheet" href="../template/default/style/metro.css" type="text/css" />
<!--[if lt IE 8]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE8.js"></script>
<![endif]-->
</head>
<body>
<div id="content">
<div class="title-bar"><h1>KKBBS 安装程序</h1></div>
<div id="main"></div><div id="btn-bar"></div></div>
<div id="load-win">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="50" height="50"><param name="movie" value="../template/default/style/loading.swf"><param name="quality" value="high"><param name="wmode" value="transparent"><embed src="../template/default/style/loading.swf" quality="high" wmode="transparent" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="50" height="50"></embed></object>
</div>
<iframe id="loader" onload="callback()"></iframe>
<script>
var content = '';
var is_ie = false;
if(document.all) is_ie = true;
function $(id){
	return document.getElementById(id);
}
function load_win(status){
	$('load-win').className = status ? 'show' : 'hide';
	$('main').style.display = status ? 'none' : '';
	$('btn-bar').style.display = status ? 'none' : '';
}
function load_page(url){
	load_win(true);
	$('loader').src = url;
}
function submit_form(formid){
	load_win(true);
	$(formid).target = 'loader';
	$(formid).submit();
}
function callback(){
	try{
		if(is_ie){
			content = document.frames['loader'].document.getElementById('content').innerHTML;
		}else{
			content = $('loader').contentDocument.getElementById('content').innerHTML;
		}
	}catch(e){
		alert('无法加载页面，请稍后重试！');
		load_win(false);
		return;
	}
	$('content').innerHTML = content;
	load_win(false);
}
load_page('?step=welcome');
</script>
</body>
</html>
EOF;
}